package com.gt.aep.web.systemManage;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gt.aep.base.entity.systemManage.SysIdentityRole;
import com.gt.aep.base.entity.systemManage.SysIdentityRoleUser;
import com.gt.aep.base.entity.systemManage.SysRoleUser;
import com.gt.aep.base.entity.systemManage.SysUser;
import com.gt.aep.base.entity.util.DateTime;
import com.gt.aep.base.entity.util.Result;
import com.gt.aep.base.service.systemManage.SysIdentityRoleService;
import com.gt.aep.base.service.systemManage.SysIdentityRoleUserService;
import com.gt.aep.base.service.systemManage.SysRoleUserService;
import com.gt.aep.base.service.systemManage.SysUserService;
import com.gt.aep.base.util.AesUtil;
import com.gt.aep.base.util.EncryptUtil;
import com.gt.aep.base.util.RsaUtil;
import net.sf.json.JSONString;
import net.sf.json.util.JSONStringer;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping("/sysUser")
public class SysUserController {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysIdentityRoleService sysIdentityRoleService;
    @Autowired
    SysIdentityRoleUserService sysIdentityRoleUserService;
    @Autowired
    SysRoleUserService sysRoleUserService;


    /**
     * 新增用户
     */
    @ResponseBody
    @RequestMapping("addUser")
    public Map<String, Object> addUser(String data,String encryptAesKey){
        //解密前端发送过来的数据
        String jsPublicKey = null;
        Map<String, Object> decData = EncryptUtil.decode(data,encryptAesKey);
        String jsAesKey = (String) decData.get("jsAesKey");
        String decrypt = (String) decData.get("data");
        //将String类型数据转化为对象
        JSONObject dataObject = new JSONObject(JSONObject.parseObject(decrypt));
        //根据前端的字段获取相对应的属性
        jsPublicKey = (String) dataObject.get("jsPublicKey");
        SysUser sysUser = (SysUser) dataObject.get("sysUser");
        String[] identityRoleIds = (String[]) dataObject.get("identityRoleIds");
        String[] sysRoleIds = (String[]) dataObject.get("sysRoleIds");
        String loginUid = (String) dataObject.get("loginUid");
        System.out.println("传入的用户对象");
        //监测新增的用户名是否已存在
        SysUser sysUser1 = sysUserService.getUserByUserName(sysUser.getUserName());
        if (sysUser1 == null){
            sysUser.setId(UUID.randomUUID().toString());
            sysUser.setCreater(loginUid);
            sysUser.setCreateTime(DateTime.time());
            //数据库操作
            int j = sysUserService.insert(sysUser);
            // 新增用户-身份角色关系表信息
            for(int k = 0; k < identityRoleIds.length; k++){
                SysIdentityRoleUser sysIdentityRoleUser = new SysIdentityRoleUser();
                sysIdentityRoleUser.setId(UUID.randomUUID().toString());
                sysIdentityRoleUser.setUid(sysUser.getId());
                sysIdentityRoleUser.setIdentityRoleId(identityRoleIds[k]);
                sysIdentityRoleUserService.insert(sysIdentityRoleUser);
            }
            // 新增用户-系统角色关系表信息
            for(int l = 0; l < sysRoleIds.length; l++){
                SysRoleUser sysRoleUser = new SysRoleUser();
                sysRoleUser.setId(UUID.randomUUID().toString());
                sysRoleUser.setUid(sysUser.getId());
                sysRoleUser.setRid(sysRoleIds[l]);
                sysRoleUserService.insert(sysRoleUser);
            }
            if (j>0){
                return Result.success("新增成功");
            }else{
                return Result.error("新增失败");
            }
        }else{
            return Result.error("用户名已存在");
        }
    }

    /**
     * 批量删除用户
     */
    @ResponseBody
    @RequestMapping("deleteUser")
    public Map<String, Object> deleteUser(String data,String encryptAesKey){
        //解密前端发送过来的数据
        String jsPublicKey = null;
        Map<String, Object> decData = EncryptUtil.decode(data,encryptAesKey);
        String jsAesKey = (String) decData.get("jsAesKey");
        String decrypt = (String) decData.get("data");
        //将String类型数据转化为对象
        JSONObject dataObject = new JSONObject(JSONObject.parseObject(decrypt));
        //根据前端的字段获取相对应的属性
        jsPublicKey = (String) dataObject.get("jsPublicKey");
        String[] ids = (String[]) dataObject.get("ids");

        //数据库操作
        //删除用户表相关信息
        int j = sysUserService.delete(ids);
        //删除关联表相关关系
        for (int i = 0; i < ids.length; i++){
            try{
                //删除系统角色-用户相关信息
                sysRoleUserService.deleteByUid(ids[i]);
                //删除身份角色-用户相关信息
                sysIdentityRoleUserService.deleteByUid(ids[i]);
            }catch (Exception e){
                return Result.error("删除角色-用户关系失败");
            }
        }
        if (j>0){
            return Result.success("删除成功");
        }else{
            return Result.error("删除失败");
        }
    }

    /**
     * 修改用户信息
     */
    @ResponseBody
    @RequestMapping("updateUser")
    public Map<String, Object> updateUser(String data, String encryptAesKey){
        //解密前端发送过来的数据
        String jsPublicKey = null;
        Map<String, Object> decData = EncryptUtil.decode(data,encryptAesKey);
        String jsAesKey = (String) decData.get("jsAesKey");
        String decrypt = (String) decData.get("data");
        //将String类型数据转化为对象
        JSONObject dataObject = new JSONObject(JSONObject.parseObject(decrypt));
        //根据前端的字段获取相对应的属性
        jsPublicKey = (String) dataObject.get("jsPublicKey");
        SysUser sysUser = (SysUser) dataObject.get("sysUser");
        String loginUid = (String) dataObject.get("loginUid");
        sysUser.setUpdater(loginUid);
        sysUser.setUpdateTime(DateTime.time());
        int j = sysUserService.update(sysUser);
        if(j>0){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败");
        }
    }

    /**
     * 修改用户密码
     */
    @ResponseBody
    @RequestMapping("changePassword")
    public Map<String, Object> changePassword(String data,String encryptAesKey){
        //解密前端发送过来的数据
        String jsPublicKey = null;
        Map<String, Object> decData = EncryptUtil.decode(data,encryptAesKey);
        String jsAesKey = (String) decData.get("jsAesKey");
        String decrypt = (String) decData.get("data");
        //将String类型数据转化为对象
        JSONObject dataObject = new JSONObject(JSONObject.parseObject(decrypt));
        //根据前端的字段获取相对应的属性
        jsPublicKey = (String) dataObject.get("jsPublicKey");
        String password = (String) dataObject.get("password");
        String userId = (String) dataObject.get("userId");
        //数据库操作
        int j = sysUserService.changePassword(userId,password);
        if (j>0){
            return Result.success("修改成功");
        }else{
            return Result.error("修改失败");
        }
    }

    /**
     * 为用户管理首页获取用户列表
     */
    @ResponseBody
    @RequestMapping("getUserList")
    public Map<String, Object> getUserList(String data, String encryptAesKey){
        //解密前端发送过来的数据
        String jsPublicKey = null;
        Map<String, Object> decData = EncryptUtil.decode(data,encryptAesKey);
        String jsAesKey = (String) decData.get("jsAesKey");
        String decrypt = (String) decData.get("data");
        //将String类型数据转化为对象
        JSONObject dataObject = new JSONObject(JSONObject.parseObject(decrypt));
        //根据前端的字段获取相对应的属性
        jsPublicKey = (String) dataObject.get("jsPublicKey");
        int curr = (int) dataObject.get("curr");
        int limit = (int) dataObject.get("limit");
        String userName = (String) dataObject.get("userName");
        String loginUid = (String) dataObject.get("loginUid");

        Map<String, Object> model = new HashedMap();
        System.out.println("jsPublicKey:"+jsPublicKey);
        //数据库查询
        List<SysUser> l = sysUserService.getUserListForIndex((curr-1)*limit,limit,userName,loginUid);
        model.put("data",l);
        model.put("limit",limit);
        model.put("count",sysUserService.getUserCountForIndex(userName,loginUid));
        //将数据存储到List中
        List<Object> dataList = new LinkedList<>();
        dataList.add(model);
        //加密要传出的数据
        return EncryptUtil.encryptData(dataList,jsPublicKey);
    }










    @RequestMapping("/try")
    public String toLogin(){
        return "try";
    }

    @ResponseBody
    @RequestMapping("getJavaPublicKey")
    public Map<String, Object> getJavaPublicKey(){
        Map<String, Object> model = new HashedMap();
        String javaPublicKey = RsaUtil.getPublicKey();
        String javaPrivateKey = RsaUtil.getPrivateKey();
        model.put("code",0);
        model.put("javaPublicKey",javaPublicKey);
        return model;
    }




}
